package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.WalletMapper;
import com.neusoft.elmboot.mapper.WalletTransactionMapper;
import com.neusoft.elmboot.po.Wallet;
import com.neusoft.elmboot.po.WalletTransaction;
import com.neusoft.elmboot.service.WalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class WalletServiceImpl implements WalletService {
    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private WalletTransactionMapper walletTransactionMapper;

    @Override
    public Wallet getWalletByUserId(String userId) {
        return walletMapper.getWalletByUserId(userId);
    }

    @Override
    @Transactional
    public boolean recharge(String userId, BigDecimal amount, String rule) {
        // 根据规则计算奖励金额
        BigDecimal bonus = calculateBonus(amount, rule);
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        boolean success = false;
        if (wallet == null) {
            // 创建钱包并设置初始余额和奖励
            wallet = new Wallet();
            wallet.setUserId(userId);
            wallet.setBalance(amount.add(bonus));
            wallet.setFrozenBalance(BigDecimal.ZERO);
            wallet.setCreditLimit(BigDecimal.ZERO);
            wallet.setIsVip(false);
            success = walletMapper.insertWallet(wallet) > 0;
        } else {
            // 更新钱包余额
            wallet.setBalance(wallet.getBalance().add(amount).add(bonus));
            success = walletMapper.updateWallet(wallet) > 0;
        }
        if (success) {
            // 记录交易流水
            WalletTransaction transaction = new WalletTransaction();
            transaction.setWalletId(wallet.getWalletId());
            transaction.setTransactionType("充值");
            transaction.setAmount(amount);
            transaction.setTimestamp(new Date());
            return walletTransactionMapper.insertTransaction(transaction) > 0;
        } else {
            return false;
        }
    }

    private BigDecimal calculateBonus(BigDecimal amount, String rule) {
        // 根据规则解析并计算奖励金额
        if (rule.contains("满1000元赠100元")) {
            return amount.divide(new BigDecimal("1000")).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        return BigDecimal.ZERO;
    }

    @Override
    @Transactional
    public boolean withdraw(String userId, BigDecimal amount) {
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        if (wallet == null || wallet.getBalance().compareTo(amount) < 0) {
            return false;
        }
        // 扣除手续费
        BigDecimal fee = amount.multiply(new BigDecimal("0.1"));
        wallet.setBalance(wallet.getBalance().subtract(amount).add(fee));
        boolean updated = walletMapper.updateWallet(wallet) > 0;
        // 记录交易流水
        WalletTransaction transaction = new WalletTransaction();
        transaction.setWalletId(wallet.getWalletId());
        transaction.setTransactionType("提现");
        transaction.setAmount(amount.negate());
        transaction.setTimestamp(new Date());
        boolean recorded = walletTransactionMapper.insertTransaction(transaction) > 0;
        return updated && recorded;
    }

    @Override
    @Transactional
    public boolean pay(String fromUserId, String toUserId, BigDecimal amount) {
        Wallet fromWallet = walletMapper.getWalletByUserId(fromUserId);
        Wallet toWallet = walletMapper.getWalletByUserId(toUserId);
        if (fromWallet == null || toWallet == null || fromWallet.getBalance().compareTo(amount) < 0) {
            return false;
        }
        fromWallet.setBalance(fromWallet.getBalance().subtract(amount));
        toWallet.setBalance(toWallet.getBalance().add(amount));
        boolean fromUpdated = walletMapper.updateWallet(fromWallet) > 0;
        boolean toUpdated = walletMapper.updateWallet(toWallet) > 0;
        // 记录交易流水
        WalletTransaction fromTransaction = new WalletTransaction();
        fromTransaction.setWalletId(fromWallet.getWalletId());
        fromTransaction.setTransactionType("支付");
        fromTransaction.setAmount(amount.negate());
        fromTransaction.setTimestamp(new Date());
        WalletTransaction toTransaction = new WalletTransaction();
        toTransaction.setWalletId(toWallet.getWalletId());
        toTransaction.setTransactionType("收款");
        toTransaction.setAmount(amount);
        toTransaction.setTimestamp(new Date());
        boolean fromRecorded = walletTransactionMapper.insertTransaction(fromTransaction) > 0;
        boolean toRecorded = walletTransactionMapper.insertTransaction(toTransaction) > 0;
        return fromUpdated && toUpdated && fromRecorded && toRecorded;
    }

    @Override
    @Transactional
    public boolean freeze(String userId, BigDecimal amount) {
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        if (wallet == null || wallet.getBalance().compareTo(amount) < 0) {
        	return false;
        }
        wallet.setFrozenBalance(wallet.getFrozenBalance().add(amount));
        wallet.setBalance(wallet.getBalance().subtract(amount));
        return walletMapper.updateWallet(wallet) > 0;
    }
        
        

    @Override
    @Transactional
    public boolean unfreeze(String userId, BigDecimal amount) {
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        if (wallet == null || wallet.getFrozenBalance().compareTo(amount) < 0) {
            return false;
        }
        wallet.setFrozenBalance(wallet.getFrozenBalance().subtract(amount));
        wallet.setBalance(wallet.getBalance().add(amount));
        return walletMapper.updateWallet(wallet) > 0;
    }

    @Override
    public boolean setCreditLimit(String userId, BigDecimal limit) {
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        if (wallet == null) {
            return false;
        }
        wallet.setCreditLimit(limit);
        return walletMapper.updateWallet(wallet) > 0;
    }

    @Override
    public boolean recordTransaction(WalletTransaction transaction) {
        return walletTransactionMapper.insertTransaction(transaction) > 0;
    }

    @Override
    @Transactional
    public boolean confirmReceive(String userId, Integer orderId) {
        WalletTransaction transaction = walletTransactionMapper.getTransactionByOrderId(orderId);
        if (transaction!= null && transaction.getTransactionType().equals("支付") && transaction.getAmount().compareTo(BigDecimal.ZERO) < 0) {
            Wallet wallet = walletMapper.getWalletByUserId(userId);
            BigDecimal amount = transaction.getAmount().negate();
            wallet.setFrozenBalance(wallet.getFrozenBalance().subtract(amount));
            wallet.setBalance(wallet.getBalance().add(amount));
            return walletMapper.updateWallet(wallet) > 0;
        }
        return false;
    }

    @Override
    public WalletTransaction checkTransactionStatus(Integer orderId) {
        return walletTransactionMapper.getTransactionByOrderId(orderId);
    }
}